/**
 * Author : cheneyliu.
 * Date   : 2016/9/20.
 * File   : map.
 */

var initComplete = false

function bMap(key) {
  if(!key){
    key = 'tzAcIFZ5xCoRwm63NcBGfoVB'
  }
  return new Promise((resolve, reject) => {
    if(window.BMap){
      resolve(window.BMap)
    }else {
      var script = document.createElement('script');
      script.type = 'text/javascript';
      script.src = 'http://api.map.baidu.com/getscript?v=2.0&ak='
        + key +'&services=&t=' + (new Date).getTime();
      script.onload = (event) => {
        resolve(window.BMap, event)
      };
      script.onerror = (error) => {
        reject(error)
      };
    }
    document.head.appendChild(script)
  });
}


function iMap() {
  return new Promise((resolve, reject) => {})
}

function initMap(self, mapBox, mapText, isAc) {
  // 百度地图
  if(self._isReady) {
    bMap().then((BMap)=> {
      var map = new BMap.Map(mapBox)
      var city = new BMap.LocalCity()

      city.get(rs => {
        map.centerAndZoom(rs.center, 13);
      })

      map.addControl(new BMap.NavigationControl({anchor: 1, type: 1}))

      var setPoint = function(p) {
        var mk = new BMap.Marker(new BMap.Point(p.lng, p.lat))
        var la = new BMap.Label('坐标: ' + p.lng + ', ' + p.lat + ' ', {offset: new BMap.Size(20, -10)})
        la.setStyle({color: "red", display: 'table', height: "20px", lineHeight: "20px", fontFamily: "微软雅黑"})
        mk.setLabel(la)
        map.addOverlay(mk)

        self.setPoint(p)
      }


      if(self.getPoint().lng != '' && self.getPoint().lat) {
        setPoint(self.getPoint())
      }

      if(isAc) {

        var ac = new BMap.Autocomplete({
          "input": mapText,
          "location": map
        })

        ac.addEventListener("onconfirm", function(e) {
          map.clearOverlays();
          var _value = e.item.value;
          var rsValue = _value.province + _value.city + _value.district
            + _value.street + _value.business;
          var local = new BMap.LocalSearch(map, {
            onSearchComplete: function() {
              var pp = local.getResults().getPoi(0).point;    //获取第一个智能搜索的结果
              map.centerAndZoom(pp, 18);
              setPoint(pp)
            }
          });
          local.search(rsValue)
        })
      } else {
        var local = new BMap.LocalSearch(map, {
          // onSearchComplete: function() {
          //   var pp = local.getResults().getPoi(0).point;    //获取第一个智能搜索的结果
          //   map.centerAndZoom(pp, 18);
          //   setPoint(pp)
          // }
          renderOptions:{map: map}

        });
        if(mapText.value !== '') {

          mapText.addEventListener('input', function(event) {
            console.log(event);
            local.search(mapText.value)
          }, false)

        }
      }


      map.addEventListener("propertychange", function(e) {
        map.clearOverlays();
        setPoint(e.point)
      })
    })
  }
}



export default bMap

export {
  bMap, initMap
}


